package com.onekbase.demo.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class TcpGatewayNioDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress("localhost", 8083));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            selector.select();
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = socketChannel.read(buffer);
                    if (bytesRead <= 0) {
                        keyIterator.remove();
                        continue;
                    }
                    buffer.flip();
                    byte[] data = new byte[buffer.remaining()];
                    buffer.get(data);
                    String receivedData = new String(data);
                    System.out.println("Received: " + receivedData);
                    String response = TcpGatewayUtils.request(receivedData,"localhost", 8084);
                    socketChannel.register(selector, SelectionKey.OP_WRITE, response);

                } else if (key.isWritable()){
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    String response = (String) key.attachment();
                    ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
                    socketChannel.write(responseBuffer);
                    socketChannel.close();
                }
                // Remove the processed key from the iterator
                keyIterator.remove();
            }
        }
    }

}